package com.nervenets.general.service;

import com.nervenets.general.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Component("us")
public class UtilService {
    public String formatKey(Object... objects) {
        return StringUtils.formatKey(objects);
    }

    public String md5(String source) {
        return DigestUtils.md5DigestAsHex(source.getBytes());
    }

    public String lowerCase(String source) {
        return source.toLowerCase();
    }

    public String upperCase(String source) {
        return source.toUpperCase();
    }

    public String header(String name) {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        if (null != attributes) {
            HttpServletRequest request = ((ServletRequestAttributes) attributes).getRequest();
            return request.getHeader(name);
        }
        return null;
    }

    public String parameter(String name) {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        if (null != attributes) {
            HttpServletRequest request = ((ServletRequestAttributes) attributes).getRequest();
            return request.getParameter(name);
        }
        return null;
    }
}
